﻿using IOP.Models.Message.MQTT;
using IOP.Models.Message.MQTT.Package;
using IOP.Pulsar.MQTT.Client;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace UAVDemo.Subscriber
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            try
            {
                string name = "";
                if (args.Length == 0)
                {
                    Console.WriteLine("客户端名?");
                    name = Console.ReadLine();
                }
                else name = args[0];
                var mqtt = new MQTTClient().Prod(prod =>
                {
                    prod.OnConnack((p, e) =>
                    {
                        Console.WriteLine(e.ConnectReturnCode.ToString());
                        p.SendSubscribe(new TopicFilter[] { new TopicFilter("/uav", QoSType.QoS0) });
                        while (p.IsConnected)
                        {
                        }
                        p.Dispose();
                    });
                    prod.OnError((p, e) =>
                    {
                        Console.WriteLine(e.Message);
                        p.Reconnect();
                    });
                    prod.OnPublish((p, c) =>
                    {
                        Console.WriteLine($"get message :{Encoding.UTF8.GetString(c.Body)}");
                    });
                    prod.OnPingresp((p, c) =>
                    {
                        Console.WriteLine("pingresp");
                    });
                });
                mqtt.Connect(option =>
                {
                    option.KeepAlive = 50;
                    option.ClientIdentifier = name;
                    option.WillFlag = false;
                    option.ServerAddress = IPAddress.Parse("127.0.0.1");
                    //option.ServerAddress = IPAddress.Parse("10.0.75.1");
                    option.Port = 2333;
                });
                while (!mqtt.IsDispose) { }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.WriteLine("client is finish");
            }
        }
    }
}
